package com.tfswx.ruleengine.database.handler.base;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Ricky
 * @date 2021/4/7
 */
public class BaseJavaBeanHandler<E> implements TypeHandler<E> {

    private Class<E> type;

    public BaseJavaBeanHandler() {
    }

    public BaseJavaBeanHandler(Class<E> type) {
        this.type = type;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        String s = null;
        if (parameter != null) {
            s = JSON.toJSONString(parameter);
        }
        ps.setString(i, s);
    }

    @Override
    public E getResult(ResultSet rs, String columnName) throws SQLException {
        String string = rs.getString(columnName);
        return JSON.parseObject(string, type);
    }

    @Override
    public E getResult(ResultSet rs, int columnIndex) throws SQLException {
        String string = rs.getString(columnIndex);
        return JSON.parseObject(string, type);
    }

    @Override
    public E getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String string = cs.getString(columnIndex);
        return JSON.parseObject(string, type);
    }
}
